package com.scqzy.shengchunqiang.sword2offer.day10;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @Description: 剑指 Offer 48. 最长不含重复字符的子字符串
 * @Author 盛春强
 * @Date 2021/8/19 17:39
 */
public class LenthOfLongestSubstring {
    public int lenthOfLongestSubstring(String s) {
        int d = 0;
        int max = 0;
        Set<Character> set = new HashSet<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            while (set.contains(c)) {
                set.remove(s.charAt(d++));
            }
            set.add(c);
            max = Math.max(max, i - d + 1);
        }
        return max;
    }

    public int lengthOfLongestSubstring1(String s) {
        Map<Character, Integer> dic = new HashMap<>();
        int max = 0, lastLen = 0;
        for (int j = 0; j < s.length(); j++) {
            int i = dic.getOrDefault(s.charAt(j), -1); // 获取索引 i
            dic.put(s.charAt(j), j); // 更新哈希表
            lastLen = lastLen < j - i ? lastLen + 1 : j - i; // dp[j - 1] -> dp[j]
            max = Math.max(max, lastLen); // max(dp[j - 1], dp[j])
        }
        return max;
    }

}
